package main

import (
	"fmt"
	"time"
)

// main
//
//	@Description: chan-有缓冲和无缓冲
func main() {
	//channelWithBuf()
	channelWithoutBufWithoutGoRouting()
	//channelWithoutBufWithGoRouting()
}

// testHasBuf
//
//	@Description: 定义的有缓冲的~ 不会报错
func channelWithBuf() {
	var ch chan int
	ch = make(chan int, 10)
	for i := 1; i <= 10; i++ {
		ch <- i
	}

}

// channelWithoutBuf00
//
//	@Description: 定义无缓冲chan ,添加元素会报错
func channelWithoutBufWithoutGoRouting() {
	var ch chan int
	ch = make(chan int)

	for i := 1; i <= 10; i++ {
		time.Sleep(time.Millisecond * 100)
		ch <- i //fatal error: all goroutines are asleep - deadlock!
	}
	for i := 1; i <= 10; i++ {
		num := <-ch
		fmt.Println("ele=", num)
	}

}

// channelWithoutBuf02
//
//	@Description:
//
// 对于无缓冲通道，必须确保有 goroutine 在接收数据时另一个 goroutine 发送数据，反之亦然。
func channelWithoutBufWithGoRouting() {
	exit := make(chan bool, 1)
	var ch chan int
	ch = make(chan int)

	go func() {
		for i := 1; i <= 10; i++ {
			time.Sleep(time.Millisecond * 100)
			ch <- i
		}
	}()

	go func() {
		for i := 1; i <= 10; i++ {
			num := <-ch
			fmt.Println("ele=", num)
		}
		exit <- true
	}()

	<-exit
	fmt.Println("主线程结束~")

}
